using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

/// <summary>
/// Summary description for FileManager
/// </summary>
public static class FileManager
{
    private const string ROOT_PATH = "~/_media";

    public static string Save(HttpPostedFile file)
    {
        return Save(file, string.Empty, GetFileName(file.FileName));
    }

    public static string Save(HttpPostedFile file, string fileName)
    {
        return Save(file, string.Empty, fileName);
    }

    public static string Save(HttpPostedFile file, string subFolderName, string fileName)
    {
        string physicalPath = HttpContext.Current.Server.MapPath(ROOT_PATH);
        string fileExtention = GetFileExtenstion(file.FileName);

        string fullPath = string.Format("{0}/{1}/{2}.{3}", physicalPath, subFolderName, fileName, fileExtention);

        file.SaveAs(fullPath);

        return fullPath;
    }

    public static string GetFileExtenstion(string fileName)
    {
        if (fileName.IndexOf(".") != -1 && fileName.IndexOf(".") != fileName.Length - 1)
        {
            return fileName.Substring(fileName.IndexOf(".") + 1);
        }

        return string.Empty;
    }

    public static string GetFileName(string fileNameWithExtension)
    {
        if (fileNameWithExtension.IndexOf(".") != -1 && fileNameWithExtension.IndexOf(".") != 0)
        {
            return fileNameWithExtension.Substring(0, fileNameWithExtension.IndexOf("."));
        }

        return string.Empty;
    }
        
}
